package com.fenxiangle.yueding.feature.mine.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.entity.bo.DeleteBo;
import com.fenxiangle.yueding.entity.bo.EventEntity;
import com.fenxiangle.yueding.entity.bo.UserCenterBo;
import com.fenxiangle.yueding.feature.mine.view.adapter.PhotoAdapter;
import com.fenxiangle.yueding.feature.mine.view.adapter.VedioAdapter;
import com.fenxiangle.yueding.framework.api.UserApi;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.rxbus2.RxBus;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.widget.SpacesItemDecoration;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class PhotoFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener,
        OnOperItemClickL, BaseQuickAdapter.OnItemChildLongClickListener {

    @BindView(R.id.rv_vedio)
    RecyclerView rvVedio;
    private ActionSheetDialog dialog;

    private List<LocalMedia> selectList;
    private UserCenterBo userCenterBo;
    private boolean isAdd;
    private boolean isMine;
    private ActionSheetDialog dialogs;

    private int mSelectPosition;

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_vedio;
    }

    private PhotoAdapter mVedioAdapter;

    @Override
    protected void initInjector() {

    }


    public static PhotoFragment getInstance(UserCenterBo userCenterBo, boolean isAdd, boolean isMine) {
        PhotoFragment sf = new PhotoFragment();
        sf.userCenterBo = userCenterBo;
        sf.isAdd = isAdd;
        sf.isMine = isMine;
        return sf;
    }

    @Override
    protected void initView() {

        rvVedio.setFocusable(false);
        final String[] stringItems = {"拍照", "从手机相册选择"};
        dialog = new ActionSheetDialog(getActivity(), stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);


        rvVedio.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        rvVedio.addItemDecoration(new SpacesItemDecoration(2, 16, false));
        mVedioAdapter = new PhotoAdapter(isAdd);
        mVedioAdapter.bindToRecyclerView(rvVedio);
        List<String> strings = new ArrayList<>();

        if (userCenterBo != null && userCenterBo.getUserImgs() != null) {
            for (int i = 0; i < userCenterBo.getUserImgs().size(); i++) {
                strings.add(userCenterBo.getUserImgs().get(i).getImage());
            }
            for (int i = 0; i < 4; i++) {
                if (strings.size() < 4) {
                    strings.add("");
                }
            }
        }
        mVedioAdapter.setNewData(strings);
        mVedioAdapter.setOnItemChildClickListener(this);
        mVedioAdapter.setOnItemChildLongClickListener(this);

        final String[] stringItems2 = {"删除"};
        dialogs = new ActionSheetDialog(getActivity(), stringItems2, null);
        dialogs.isTitleShow(false);
        dialogs.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<String> strings = new ArrayList<>();
                DeleteBo deleteBo = new DeleteBo();
                strings.add(userCenterBo.getUserImgs().get(mSelectPosition).getId());
                deleteBo.setImgIds(strings);
                deleteVedio(deleteBo);
                dialogs.dismiss();
            }
        });


    }


    @Override
    protected void initData() {
        RxBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()){
            case R.id.btn_show_upload:
                if (dialog != null) dialog.show();
                break;
            case R.id.photo_img:
                Intent intent = new Intent(getActivity(), ImageActivity.class);
                intent.putExtra("images", (Serializable) userCenterBo.getUserImgs());
                intent.putExtra("pos", position);
                 startActivity(intent);
                break;
        }

    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style1)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .selectionMedia(selectList)// 是否传入已选图片
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case 1:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style1)
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(false)
                        .enableCrop(true)// 是否裁剪
                        .compress(true)// 是否压缩
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .selectionMedia(selectList)// 是否传入已选图片
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;

        }

        dialog.dismiss();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    uploadImages(selectList);
                    break;
            }
        }
    }

    private void uploadImages(List<LocalMedia> images) {
        List<MultipartBody.Part> bodyHashMap = new ArrayList<>();
        if (images != null && !images.isEmpty()) {
            for (int i = 0; i < images.size(); i++) {
                File file = new File(images.get(i).getCompressPath());
                RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("userImgs", file.getName(), requestFile);
                bodyHashMap.add(filePart);
            }

            AM.api().createApiService(UserApi.class).addImages(bodyHashMap)
                    .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            showLoading(d);
                        }

                        @Override
                        public void onNext(String s) {
                            dismissLoading();
                            showMsg("上传成功！");
                            RxBus.getDefault().post(new EventEntity(8, s));
                        }

                        @Override
                        public void onError(Throwable e) {
                            dismissLoading();
                            showMsg("上传失败！" + e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        }

    }


    @Override
    public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
        if (isMine) {
            if (dialogs != null) dialogs.show();
            mSelectPosition = position;
        }
        return false;
    }

    private void deleteVedio(DeleteBo urls) {
        AM.api().createApiService(UserApi.class)
                .deletePhoto(urls)
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading(d);
                    }

                    @Override
                    public void onNext(String s) {
                        dismissLoading();
                        showMsg("删除成功!");
                        RxBus.getDefault().post(new EventEntity(888, "a"));
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        showMsg(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });

    }


}
